package services

import (
	"github.com/gomodule/redigo/redis"
	"ir/core/db"
	"ir/models/structs"
	"log"
)

func Subscribe() {
	conn := db.GetRedis()
	psc := redis.PubSubConn{Conn: conn}

	channels := []string{"buy", "sell", "test"}
	psc.Subscribe(redis.Args{}.AddFlat(channels)...)

	// Start a goroutine to receive notifications from the server.
	go func() {
		defer psc.Close()
		for {
			switch v := psc.Receive().(type) {
			case redis.Message:
				if v.Channel == "buy" || v.Channel == "sell" {
					var newOrder = new(structs.Order)
					newOrder.FromJSON(v.Data)
					//key := order.Key()
					//newCacheOrder := order.SymbolOrder
					//rc := db.GetRedis()
					orderBook := newOrder.ToOrderBook()
					var err error
					var affected int64
					affected, err = db.Conn().Insert(orderBook)

					if err != nil {
						log.Println(err)
						continue
					}

					if affected == 0 {
						log.Println("入库失败")
						continue
					}

					var matchOrders []structs.Order
					//var idx int64
					//var rowStr string
					matchOrders, err = FindMatchOrders(*newOrder) // 返回匹配的订单
					if err != nil {
						log.Println(err)
						continue
					}
					matchNum := len(matchOrders)
					log.Println("##########")
					log.Println(newOrder)
					log.Println(matchOrders)
					if matchNum > 0 { // 匹配到
						//var surplusOrder structs.Order
						err = DealMatchedOrders(*newOrder, matchOrders)
						if err != nil {
							log.Println("err", err)
							continue
						}
					} else {
						err = PushToQueue(*newOrder)
						if err != nil {
							log.Println("err", err)
							continue
						}
					}
					//if surplusOrder.Amount > 0 {
					//	newCacheOrder = surplusOrder.SymbolOrder
					//	// 1 买 升
					//	// 2 卖 降
					//	if newCacheOrder.Side == 1 {
					//		idx, rowStr, err = AddBuyOrder(key, newCacheOrder)
					//		if err != nil {
					//			log.Println("搜索错误", err)
					//		} else {
					//			if rowStr != "" {
					//				_, err = rc.Do("LINSERT", key, "AFTER", rowStr, string(newCacheOrder.ToJSON()))
					//			} else {
					//				if idx == 0 {
					//					_, err = rc.Do("RPUSH", key, string(newCacheOrder.ToJSON()))
					//				} else {
					//					_, err = rc.Do("LPUSH", key, string(newCacheOrder.ToJSON()))
					//				}
					//			}
					//		}
					//	} else if newCacheOrder.Side == 2 {
					//		idx, rowStr, err = AddSellOrder(key, newCacheOrder)
					//		if err != nil {
					//			log.Println("搜索错误", err)
					//		} else {
					//			if rowStr != "" {
					//				_, err = rc.Do("LINSERT", key, "BEFORE", rowStr, string(newCacheOrder.ToJSON()))
					//			} else {
					//				if idx == 0 {
					//					_, err = rc.Do("LPUSH", key, string(newCacheOrder.ToJSON()))
					//				} else {
					//					_, err = rc.Do("RPUSH", key, string(newCacheOrder.ToJSON()))
					//				}
					//			}
					//		}
					//	}
					//}
				} else {
					if v.Channel == "test" {
						db.GetRedis().Do("lpush", "test", string(v.Data))
					}
					log.Println(v.Channel, string(v.Data))
				}
			case redis.Subscription:
				log.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
			}
		}
	}()
}

func PushToQueue(order structs.Order) (err error) {
	if order.Amount > 0 {
		key := order.Key()
		// 1 买 升
		// 2 卖 降

		if order.Side == 1 {
			err = AddBuyOrder(key, order.SymbolOrder)
			if err != nil {
				log.Println("搜索错误", err)
			}
		} else if order.Side == 2 {
			err = AddSellOrder(key, order.SymbolOrder)
			if err != nil {
				log.Println("搜索错误", err)
			}
		}
	}
	return
}
